using Aliyun.OSS;
using Infrastructure.Attribute;
using Infrastructure.Model;
using JTZY.Common;
using JTZY.Model.Brand;
using JTZY.Model.Business;
using JTZY.Model.Goods;
using JTZY.Model.Goods.Dto;
using JTZY.Model.Order.Dto;
using JTZY.Model.Product;
using JTZY.Model.Stock;
using JTZY.Repository;
using JTZY.Service.Business.IBusinessService;
using JTZY.Service.Goods.IGoodsService;
using JTZY.Service.Stock.IStockService;
using JTZY.ServiceCore.Services;
using Microsoft.Extensions.Options;
using SqlSugar;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using static Org.BouncyCastle.Asn1.Cmp.Challenge;


namespace JTZY.Service.Goods
{
    /// <summary>
    /// 良品仓Service业务层处理
    /// </summary>
    [AppService(ServiceType = typeof(ICorecmsuserstockService), ServiceLifetime = LifeTime.Transient)]
    public class CorecmsuserstockService : BaseService<Corecmsuserstock>, ICorecmsuserstockService
    {
        private readonly ICorecmsgoodsService CorecmsgoodsService;
        private readonly ITransferorderService _TransferorderService;
        private readonly ICorecmsuserService _corecmsuserService;
        public CorecmsuserstockService(ICorecmsgoodsService corecmsgoodsService
            , ICorecmsuserService corecmsuserService
            , ITransferorderService transferorderService)
        {
            CorecmsgoodsService = corecmsgoodsService;
            _TransferorderService = transferorderService;
            _corecmsuserService = corecmsuserService;
        }
        /// <summary>
        /// 查询良品仓列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<ProductStockDto> GetList(CorecmsuserstockQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                .LeftJoin<Corecmsgoods>((aprod, goods) => aprod.GoodId == goods.Id)
                .LeftJoin<Corecmsproducts>((aprod, goods, prod) => aprod.ProductId == prod.Id)
                .LeftJoin<Corecmsbrand>((aprod, goods, prod, brand) => goods.BrandId == brand.Id)
                .Where((aprod, goods, prod, brand) => aprod.UserId == parm.UserId)
                .WhereIF(parm.GoodsId.HasValue, (aprod, goods, prod, brand) => aprod.GoodId == parm.GoodsId.Value)
                .WhereIF(!string.IsNullOrEmpty(parm.categoryArr), (aprod, goods, prod, brand) => goods.categoryArr.StartsWith(parm.categoryArr))
                .WhereIF(parm.HasStock, (aprod, goods, prod, brand) => aprod.Stock > 0 || aprod.MinStock > 0)
                //.WhereIF(parm.mini.HasValue && parm.mini == 1, (aprod, goods, prod) => aprod.MinStock > 0)
                .WhereIF(!string.IsNullOrEmpty(parm.sn), (aprod, goods, prod, brand) => prod.Sn.Contains(parm.sn) || prod.SpesDesc.ToLower().Contains(parm.sn.ToLower()) || prod.Barcode.Contains(parm.sn))
                .Select((aprod, goods, prod, brand) => new ProductStockDto
                {
                    Id = aprod.Id,
                    SkuImage = !string.IsNullOrWhiteSpace(aprod.SkuImage) ? aprod.SkuImage : goods.Image,
                    Sn = prod.Sn,
                    ProductId = prod.Id,
                    SkuName = prod.SkuName,
                    Stock = aprod.Stock ?? 0,
                    MinStock = aprod.MinStock ?? 0,
                    VIP0 = aprod.Vip0,
                    VIP1 = aprod.Vip1,
                    VIP2 = aprod.Vip2,
                    VIP3 = aprod.Vip3,
                    VIP4 = aprod.Vip4,
                    BarCode = prod.Barcode,
                    CostPrice = aprod.ProductCostPrice,
                    Atrr = "铺货商品",
                    SkuLocation = aprod.SkuLocation,
                    Marketable = aprod.Marketable ?? 0,
                    CategoryId = goods.GoodsCategoryId,
                    FirstCategoryId = goods.GoodsFirstCategoryId,
                    SecondCategoryId = goods.GoodsSecondCategoryId,
                    SkuBrandId = aprod.SkubrandId.HasValue ? aprod.SkubrandId.Value : goods.BrandId,
                    SkuBrandName = brand.Name,
                    TotalStock = (aprod.Stock ?? 0) + (aprod.MinStock ?? 0),
                    CreateTime = aprod.CreateTime,
                })
                //.OrderBy("CreateTime asc")
                .ToPage<ProductStockDto>(parm);

            var ext = Queryable().Where(pi => pi.UserId == parm.UserId)
            .LeftJoin<Corecmsgoods>((pi, goods) => pi.GoodId == goods.Id)
            .LeftJoin<Corecmsproducts>((pi, goods, prod) => pi.ProductId == prod.Id)
            .Where((pi, goods, prod) => pi.UserId == parm.UserId)
            .WhereIF(parm.GoodsId.HasValue, (pi, goods, prod) => pi.GoodId == parm.GoodsId.Value)
            .WhereIF(!string.IsNullOrEmpty(parm.categoryArr), (pi, goods, prod) => goods.categoryArr.StartsWith(parm.categoryArr))
            .WhereIF(!string.IsNullOrEmpty(parm.sn), (pi, goods, prod) => prod.Sn.Contains(parm.sn) || prod.Barcode.Contains(parm.sn) || pi.SkuName.Contains(parm.sn))
            .Select((pi, goods) => new
            {
                Stock = SqlFunc.AggregateSumNoNull(pi.Stock),
                MinStock = SqlFunc.AggregateSumNoNull(pi.MinStock),
                Amount = SqlFunc.AggregateSumNoNull(SqlFunc.IsNull(pi.Stock, 0) * pi.ProductCostPrice + SqlFunc.IsNull(pi.MinStock, 0) * pi.ProductCostPrice)
            }).First();

            //var sumExt=ext.Select(t => new
            //{
            //    Stock = SqlFunc.AggregateSumNoNull(t.Stock),
            //    MinStock = SqlFunc.AggregateSumNoNull(t.MinStock),
            //    Amount = SqlFunc.AggregateMin(t.Amount)
            //}).ToList();

            response.Extra = new Dictionary<string, object>()
            {
                { "CateNums",response.TotalNum },
                { "Nums",ext.Stock+ext.MinStock },
                { "Amount",ext.Amount }
            };

            return response;
        }

        /// <summary>
        /// 查询小仓列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<ProductStockDto> GetKtList(CorecmsuserstockQueryDto parm)
        {
            //var predicate = QueryExp(parm);
            var query = Context.Queryable<Prodinfo>().Where(pi => pi.UserId == parm.UserId && pi.UserCusId > 0 && pi.Status == 1 && pi.IsReturn == 0)
                .WhereIF(parm.cusUserId.HasValue, pi => pi.UserCusId == parm.cusUserId).GroupBy(pi => new { pi.ProductId, pi.UserId })
                .Select(pi => new { ProductId = pi.ProductId, pi.UserId, Stock = SqlFunc.AggregateSum<int>(1) });
            var response = query
                .LeftJoin<Corecmsuserstock>((pi, aprod) => pi.UserId == aprod.UserId && pi.ProductId == aprod.ProductId)
                .LeftJoin<Corecmsgoods>((pi, aprod, goods) => aprod.GoodId == goods.Id)
                .LeftJoin<Corecmsproducts>((pi, aprod, goods, prod) => aprod.ProductId == prod.Id)
                .Where((pi, aprod, goods, prod) => aprod.UserId == parm.UserId)
                .WhereIF(!string.IsNullOrEmpty(parm.categoryArr), (pi, aprod, goods, prod) => goods.categoryArr.StartsWith(parm.categoryArr))
                .WhereIF(!string.IsNullOrEmpty(parm.sn), (pi, aprod, goods, prod) => prod.Sn.Contains(parm.sn) || prod.Barcode.Contains(parm.sn) || aprod.SkuName.Contains(parm.sn))
                .Select((pi, aprod, goods, prod) => new ProductStockDto
                {
                    Id = aprod.Id,
                    SkuImage = !string.IsNullOrWhiteSpace(aprod.SkuImage) ? aprod.SkuImage : goods.Image,
                    Sn = prod.Sn,
                    SkuName = aprod.SkuName,
                    Stock = pi.Stock,
                    MinStock = aprod.MinStock ?? 0,
                    BarCode = prod.Barcode,
                    CostPrice = aprod.ProductCostPrice,
                    Atrr = "铺货商品",
                    SkuLocation = aprod.SkuLocation,
                    Marketable = aprod.Marketable ?? 0,
                    CategoryId = goods.GoodsCategoryId,
                    SkuBrandId = aprod.SkubrandId.HasValue ? aprod.SkubrandId.Value : goods.BrandId,
                    SkuBrandName = "",
                    CreateTime = aprod.CreateTime,
                    ProductId = aprod.ProductId,
                })
                .OrderBy("Id asc")
                .ToPage<ProductStockDto>(parm);

            if (parm.cusUserId.HasValue)
            {
                var cusUser = _corecmsuserService.Queryable().Where(u => u.Id == parm.cusUserId).First();

                var ext = Context.Queryable<Corecmsuserstock>().Where(pi => pi.UserId == parm.cusUserId)
                 .LeftJoin<Corecmsuserstock>((pi, pi2) => pi.ProductId == pi2.ProductId && pi2.UserId == parm.UserId)
                .LeftJoin<Corecmsgoods>((pi, pi2, goods) => pi.GoodId == goods.Id)
                .LeftJoin<Corecmsproducts>((pi, pi2, goods, prod) => pi.ProductId == prod.Id)
                .WhereIF(!string.IsNullOrEmpty(parm.categoryArr), (pi, pi2, goods, prod) => goods.categoryArr.StartsWith(parm.categoryArr))
                .WhereIF(!string.IsNullOrEmpty(parm.sn), (pi, pi2, goods, prod) => prod.Sn.Contains(parm.sn) || prod.Barcode.Contains(parm.sn) || pi.SkuName.Contains(parm.sn))
                .WhereIF(parm.cusUserId.HasValue, pi => SqlFunc.Subqueryable<Corecmsuserstock>().Where(o => o.UserId == parm.cusUserId && o.ProductId == pi.ProductId).Any())
                .Select((pi, pi2, goods, prod) => new
                {
                    CateNums = SqlFunc.AggregateSum<int>(1),
                    Nums = SqlFunc.AggregateSum(SqlFunc.IsNull(pi.Stock, 0)),
                    Amount = SqlFunc.AggregateSumNoNull(SqlFunc.IsNull(pi.Stock, 0) * pi2.ProductCostPrice),
                    Vip0 = SqlFunc.AggregateSumNoNull(SqlFunc.IsNull(pi.Stock, 0) * pi2.Vip0),
                    Vip1 = SqlFunc.AggregateSumNoNull(SqlFunc.IsNull(pi.Stock, 0) * pi2.Vip1),
                    Vip2 = SqlFunc.AggregateSumNoNull(SqlFunc.IsNull(pi.Stock, 0) * pi2.Vip2),
                    Vip3 = SqlFunc.AggregateSumNoNull(SqlFunc.IsNull(pi.Stock, 0) * pi2.Vip3),
                    Vip4 = SqlFunc.AggregateSumNoNull(SqlFunc.IsNull(pi.Stock, 0) * pi2.Vip4),

                }).First();

                decimal Amount = 0;
                switch (cusUser.Level)
                {
                    case "0":
                        Amount = ext.Vip0.HasValue ? ext.Vip0.Value : 0;
                        break;
                    case "1":
                        Amount = ext.Vip1.HasValue ? ext.Vip1.Value : 0;
                        break;
                    case "2":
                        Amount = ext.Vip2.HasValue ? ext.Vip2.Value : 0;
                        break;
                    case "3":
                        Amount = ext.Vip3.HasValue ? ext.Vip3.Value : 0;
                        break;
                    case "4":
                        Amount = ext.Vip4.HasValue ? ext.Vip4.Value : 0;
                        break;
                }
                response.Extra = new Dictionary<string, object>()
            {
                { "CateNums",ext.CateNums },
                { "Nums",ext.Nums },
                { "Amount",Amount }
            };
            }
            else
            {
                var ext = Context.Queryable<Corecmsuserstock>().Where(pi => pi.UserId == parm.UserId && pi.MinStock > 0)
                .LeftJoin<Corecmsgoods>((pi, goods) => pi.GoodId == goods.Id)
                .LeftJoin<Corecmsproducts>((pi, goods, prod) => pi.ProductId == prod.Id)
                .Where((pi, goods, prod) => pi.UserId == parm.UserId)
                .WhereIF(!string.IsNullOrEmpty(parm.categoryArr), (pi, goods, prod) => goods.categoryArr.StartsWith(parm.categoryArr))
                .WhereIF(!string.IsNullOrEmpty(parm.sn), (pi, goods, prod) => prod.Sn.Contains(parm.sn) || prod.Barcode.Contains(parm.sn) || pi.SkuName.Contains(parm.sn))
                .WhereIF(parm.cusUserId.HasValue, pi => SqlFunc.Subqueryable<Corecmsuserstock>().Where(o => o.UserId == parm.cusUserId && o.ProductId == pi.ProductId).Any())
                //.Select(pi => new { ProductId = pi.ProductId, Stock = SqlFunc.AggregateSum<int>(1) });
                .Select((pi, goods, prod) => new
                {
                    CateNums = SqlFunc.AggregateSum<int>(1),
                    Nums = SqlFunc.AggregateSum(pi.MinStock),
                    Amount = SqlFunc.AggregateSumNoNull(pi.MinStock * pi.ProductCostPrice)
                }).First();

                response.Extra = new Dictionary<string, object>()
            {
                { "CateNums",ext.CateNums },
                { "Nums",ext.Nums },
                { "Amount",ext.Amount }
            };
            }


            return response;
        }

        /// <summary>
        /// 查询小仓列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<ProductStockDto> GeKtList(CorecmsuserstockQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                .LeftJoin<Corecmsgoods>((aprod, goods) => aprod.GoodId == goods.Id)
                .LeftJoin<Corecmsproducts>((aprod, goods, prod) => aprod.ProductId == prod.Id)
                .Where((aprod, goods, prod) => aprod.UserId == parm.UserId)
                .WhereIF(parm.mini.HasValue && parm.mini == 1, (aprod, goods, prod) => aprod.MinStock > 0)
                .WhereIF(!string.IsNullOrEmpty(parm.sn), (aprod, goods, prod) => prod.Sn.Contains(parm.sn) || goods.Name.Contains(parm.sn) || prod.SkuName.Contains(parm.sn))
                .Select((aprod, goods, prod) => new ProductStockDto
                {
                    Id = aprod.Id,
                    SkuImage = !string.IsNullOrWhiteSpace(aprod.SkuImage) ? aprod.SkuImage : goods.Image,
                    Sn = prod.Sn,
                    SkuName = aprod.SkuName,
                    Stock = aprod.Stock ?? 0,
                    MinStock = aprod.MinStock ?? 0,
                    VIP0 = aprod.Vip0,
                    VIP1 = aprod.Vip1,
                    VIP2 = aprod.Vip2,
                    VIP3 = aprod.Vip3,
                    VIP4 = aprod.Vip4,
                    BarCode = prod.Barcode,
                    CostPrice = aprod.ProductCostPrice,
                    Atrr = "铺货商品",
                    SkuLocation = aprod.SkuLocation,
                    Marketable = aprod.Marketable ?? 0,
                    CategoryId = goods.GoodsCategoryId,
                    SkuBrandId = aprod.SkubrandId.HasValue ? aprod.SkubrandId.Value : goods.BrandId,
                    SkuBrandName = "",
                    TotalStock = aprod.MinStock ?? 0,
                    CreateTime = aprod.CreateTime,
                })
                //.OrderBy("CreateTime asc")
                .ToPage<ProductStockDto>(parm);

            return response;
        }

        /// <summary>
        /// 查客户良品仓列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<ProductStockDto> GetCustomerList(CorecmsuserstockQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                .LeftJoin<Corecmsuser>((aprod, user) => aprod.UserId == user.ParentId)
                .LeftJoin<Corecmsgoods>((aprod, user, goods) => aprod.GoodId == goods.Id)
                .LeftJoin<Corecmsproducts>((aprod, user, goods, prod) => aprod.ProductId == prod.Id)
                .Where((aprod, user, goods, prod) => aprod.UserId == parm.UserId)
                .WhereIF(!string.IsNullOrEmpty(parm.categoryArr), (aprod, user, goods, prod) => goods.categoryArr.StartsWith(parm.categoryArr))
                .WhereIF(parm.mini.HasValue && parm.mini == 1, (aprod, user, goods, prod) => aprod.MinStock > 0)
                .WhereIF(!string.IsNullOrEmpty(parm.sn), (aprod, user, goods, prod) => prod.Sn.Contains(parm.sn) || goods.Name.Contains(parm.sn) || prod.SkuName.Contains(parm.sn))
                .Select((aprod, user, goods, prod) => new ProductStockDto
                {
                    Id = aprod.Id,
                    SkuImage = !string.IsNullOrWhiteSpace(aprod.SkuImage) ? aprod.SkuImage : goods.Image,
                    Sn = prod.Sn,
                    SkuName = prod.SkuName,
                    Stock = SqlFunc.Subqueryable<Prodinfo>().Where(s => s.ProductId == aprod.ProductId && s.UserId == user.Id).Select(s => SqlFunc.AggregateSumNoNull<int>(1)),
                    BarCode = prod.Barcode,
                    CostPrice = user.Level == "0" ? aprod.Vip0 : user.Level == "1" ? aprod.Vip1 : user.Level == "2" ? aprod.Vip2 : user.Level == "3" ? aprod.Vip3 : aprod.Vip4,
                    SkuLocation = aprod.SkuLocation,
                    Marketable = aprod.Marketable ?? 0,
                    CategoryId = goods.GoodsCategoryId,
                    FirstCategoryId = goods.GoodsFirstCategoryId,
                    SecondCategoryId = goods.GoodsSecondCategoryId,
                    SkuBrandId = aprod.SkubrandId.HasValue ? aprod.SkubrandId.Value : goods.BrandId,
                    SkuBrandName = "",
                    CreateTime = aprod.CreateTime,
                })
                //.OrderBy("CreateTime asc")
                .ToPage<ProductStockDto>(parm);

            return response;
        }

        /// <summary>
        /// 上下架
        /// </summary>
        /// <param name="modal"></param>
        /// <returns></returns>
        public int Marketable(Corecmsuserstock model)
        {
            if (model.Marketable == 1)
            {
                var us = Queryable().Where(u => u.Id == model.Id).First();
                return Update(u => u.Id == model.Id, it => new Corecmsuserstock()
                {
                    Marketable = model.Marketable,
                    Vip0 = us.ProductCostPrice + us.InvalVip0.Value,
                    Vip1 = us.ProductCostPrice + us.InvalVip1.Value,
                    Vip2 = us.ProductCostPrice + us.InvalVip2.Value,
                    Vip3 = us.ProductCostPrice + us.InvalVip3.Value,
                    Vip4 = us.ProductCostPrice + us.InvalVip4.Value,
                    SaleStock = us.Stock.Value,
                    UpdateTime = DateTime.Now
                });

            }
            else
            {
                return Update(u => u.Id == model.Id, it => new Corecmsuserstock() { Marketable = model.Marketable, UpdateTime = DateTime.Now });
            }
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Corecmsuserstock GetInfo(long Id)
        {
            var response = Queryable()
                .Where(x => x.Id == Id)
                .First();

            return response;
        }

        /// <summary>
        /// 添加良品仓
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Corecmsuserstock AddCorecmsuserstock(Corecmsuserstock model)
        {
            return Insertable(model).ExecuteReturnEntity();
        }

        /// <summary>
        /// 修改良品仓
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateCorecmsuserstock(Corecmsuserstock model)
        {
            return Update(model, true);
        }

        /// <summary>
        /// 查询导出表达式
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static Expressionable<Corecmsuserstock> QueryExp(CorecmsuserstockQueryDto parm)
        {
            var predicate = Expressionable.Create<Corecmsuserstock>();

            return predicate;
        }


        public bool UpdateVipPrice(UpdateVipPriceDto parm)
        {
            List<Corecmsuserstock> upLst = new List<Corecmsuserstock>();

            List<int> cateIds = new List<int>();
            cateIds = parm.categories.Select(it => it.id).ToList();
            var goods = Context.Queryable<Corecmsgoods>().Where(it => cateIds.Contains(it.GoodsCategoryId.Value)).ToList();
            if (goods != null && goods.Count > 0)
            {
                List<int> goodIds = new List<int>();
                goodIds = goods.Select(it => it.Id).ToList();
                var res = UseTran(() =>
                {
                    var userStocks = Context.Queryable<Corecmsuserstock>().Where(it => it.UserId == parm.UserId && goodIds.Contains(it.GoodId)).ToList();
                    if (userStocks != null && userStocks.Count > 0)
                    {
                        foreach (var item in userStocks)
                        {
                            if (item.ProductCostPrice <= 0) continue;
                            if (parm.range == "0" && item.InvalVip0.HasValue) continue;
                            if (parm.type == "0")
                            {
                                item.InvalVip0 = item.ProductCostPrice * (parm.vip0 / 100);
                                item.InvalVip1 = item.ProductCostPrice * (parm.vip1 / 100);
                                item.InvalVip2 = item.ProductCostPrice * (parm.vip2 / 100);
                                item.InvalVip3 = item.ProductCostPrice * (parm.vip3 / 100);
                                item.InvalVip4 = item.ProductCostPrice * (parm.vip4 / 100);

                            }
                            else
                            {
                                item.InvalVip0 = parm.vip0;
                                item.InvalVip1 = parm.vip1;
                                item.InvalVip2 = parm.vip2;
                                item.InvalVip3 = parm.vip3;
                                item.InvalVip4 = parm.vip4;

                            }

                            item.Vip0 = item.ProductCostPrice + item.InvalVip0.Value;
                            item.Vip1 = item.ProductCostPrice + item.InvalVip1.Value;
                            item.Vip2 = item.ProductCostPrice + item.InvalVip2.Value;
                            item.Vip3 = item.ProductCostPrice + item.InvalVip3.Value;
                            item.Vip4 = item.ProductCostPrice + item.InvalVip4.Value;

                            upLst.Add(item);
                        }
                    }
                    if (upLst.Count > 0)
                    {
                        Context.Updateable<Corecmsuserstock>(upLst).UpdateColumns(it =>
                        new
                        {
                            it.InvalVip0,
                            it.InvalVip1,
                            it.InvalVip2,
                            it.InvalVip3,
                            it.InvalVip4,
                            it.Vip0,
                            it.Vip1,
                            it.Vip2,
                            it.Vip3,
                            it.Vip4,
                        })
                        .ExecuteCommand();
                        //UpdateRange(upLst)
                    }
                });

                return res.Data;
            }

            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="goodId"></param>
        /// <returns></returns>
        public List<Corecmsuserstock> GetUserStockList(long userId, int goodId)
        {
            return Queryable().Where(s => s.UserId == userId && s.GoodId == goodId).ToList();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public UserStockDto GetUserStock(CorecmsuserstockQueryDto parm)
        {

            var response = Queryable()
                 .LeftJoin<Corecmsgoods>((aprod, goods) => aprod.GoodId == goods.Id)
                 .LeftJoin<Corecmsproducts>((aprod, goods, prod) => aprod.ProductId == prod.Id)
                 .Where((aprod, goods, prod) => aprod.UserId == parm.UserId)
                 .WhereIF(!string.IsNullOrEmpty(parm.categoryArr), (aprod, goods, prod) => goods.categoryArr.StartsWith(parm.categoryArr))
                 .WhereIF(!string.IsNullOrEmpty(parm.sn), (aprod, goods, prod) => prod.Sn.Contains(parm.sn) || goods.SpesDesc.Contains(parm.sn) || prod.Barcode.Contains(parm.sn))
                 .Select((aprod, goods, prod) => new
                 {
                     Nums = SqlFunc.AggregateCount(aprod.Id),
                     Stock = SqlFunc.AggregateSum(aprod.Stock ?? 0),
                 })
                 .ToList();


            UserStockDto userStockDto = new UserStockDto();
            userStockDto.nums = response != null ? response[0].Nums : 0;
            userStockDto.stock = response != null ? response[0].Stock : 0;


            if (!string.IsNullOrEmpty(parm.sn) || !string.IsNullOrEmpty(parm.categoryArr))
            {
                userStockDto.amount = Context.Queryable<Prodinfo>()
                .LeftJoin<Corecmsproducts>((aprod, prod) => aprod.ProductId == prod.Id)
                .LeftJoin<Corecmsgoods>((aprod, prod, goods) => prod.GoodsId == goods.Id)
                .Where((aprod, prod, goods) => aprod.UserId == parm.UserId)
                .WhereIF(!string.IsNullOrEmpty(parm.categoryArr), (aprod, prod, goods) => goods.categoryArr.StartsWith(parm.categoryArr))
                .WhereIF(!string.IsNullOrEmpty(parm.sn), (aprod, prod, goods) => prod.Sn.Contains(parm.sn) || goods.SpesDesc.Contains(parm.sn) || prod.Barcode.Contains(parm.sn))
                .Sum((aprod, prod, goods) => aprod.CostPrice);
            }
            else
            {
                userStockDto.amount = Context.Queryable<Prodinfo>().Where(it => it.UserId == parm.UserId).Sum(it => it.CostPrice);
            }
            return userStockDto;
        }

        public List<WarehouseDto> QueryWarehouseList(long userId)
        {
            var response = Context.Queryable<Prodinfo>()
                                .Where(pi => pi.UserId == userId && pi.UserCusId > 0)
                                .LeftJoin<Corecmsuser>((pi, u) => pi.UserCusId == u.Id)
                                .Distinct()
                                .Select((pi, u) => new WarehouseDto
                                {
                                    cusId = u.Id,
                                    WarehouseName = u.UserName
                                }).ToList();

            return response;
        }
        public bool UpdateStockWarnLine(StockWarnUpdataDto parm)
        {
            List<Corecmsuserstock> upLst = new List<Corecmsuserstock>();
            var res = UseTran(() =>
                {
                    if (parm.details != null && parm.details.Count > 0)
                    {
                        // 当 details 有值时，按 goodsId, productId, userId 来更新
                        foreach (var detail in parm.details)
                        {
                            var updateResult = Context.Updateable<Corecmsuserstock>()
                                .SetColumns(it => new Corecmsuserstock
                                {
                                    StockWarn = detail.stockWarn,
                                    stockWarnType = detail.stockWarnType
                                })
                                .Where(it => it.GoodId == detail.goodsId && it.ProductId == detail.productId && it.UserId == parm.userId)
                                .ExecuteCommand();
                        }
                    }
                    else
                    {
                        // 当 details 无值时，按 userId 来更新所有属于该 userId 下的数据
                        var updateResult = Context.Updateable<Corecmsuserstock>()
                            .SetColumns(it => new Corecmsuserstock
                            {
                                StockWarn = parm.globalStockWarn,
                                stockWarnType = parm.globalStockWarnType
                            })
                            .Where(it => it.UserId == parm.userId)
                            .ExecuteCommand();
                    }
                });

            return res.Data;
        }
        public async Task<PurStockManageMasterhDto> GetPurStockWarnLineByGoodsId(PurStockManageDetailQueryDto parm)
        {
            var model = new PurStockManageMasterhDto();

            var goodsinfo = await Context.Queryable<Corecmsgoods>().Where(e => e.Id == parm.goodsId).FirstAsync();

            model.prodId = goodsinfo.Id;
            model.prodName = goodsinfo.Name;
            model.pic = goodsinfo.Image;

            var dto = Context.Queryable<Corecmsusergoods>()
                     .LeftJoin<Corecmsbrand>((usergoods, brand) => usergoods.GoodBrand == brand.Id)
                     .LeftJoin<Corecmsuserstock>((usergoods, brand, stock) => usergoods.GoodId == stock.GoodId && usergoods.UserId == stock.UserId)
                     .Where((usergoods, brand, stock) => usergoods.UserId == parm.userId)
                     .WhereIF(parm.goodsId > 0, (usergoods, brand, stock) => usergoods.GoodId == parm.goodsId)
                     .Select((usergoods, brand, stock) => new PurStockManageDetailDto
                     {
                         distributionProdId = usergoods.GoodId,
                         distributionSkuId = stock.ProductId,
                         skuId = stock.ProductId,
                         skuCode = stock.Sn,
                         skuName = stock.SkuName,
                         prodCode69 = stock.BarCode,
                         skuStocks = stock.Stock,
                         sellerSkuStocks = 0,
                         transitSkuNum = 0,
                         distributionStocks = stock.PurStock,
                         stockWarningLine = stock.StockWarn,
                         stockWarnType = stock.stockWarnType.ToString(),
                         brandName = brand.Name,
                         costPrice = stock.ProductCostPrice,
                         normalPrice = stock.Vip0,
                         vip1Price = stock.Vip1,
                         vip2Price = stock.Vip2,
                         vip3Price = stock.Vip3,
                         vip4Price = stock.Vip4,
                         delFlag = stock.IsDel
                     })
                     .ToList();
            model.distributionSkuVOS = dto;
            return model;

        }
        public async Task<PurStockManageMasterhDto> GetPurStockDetailByGoodsId(PurStockManageDetailQueryDto parm)
        {
            var model = new PurStockManageMasterhDto();

            var goodsinfo = await Context.Queryable<Corecmsgoods>().Where(e => e.Id == parm.goodsId).FirstAsync();

            model.prodId = goodsinfo.Id;
            model.prodName = goodsinfo.Name;
            model.pic = goodsinfo.Image;

            var dto = Context.Queryable<Corecmsusergoods>()
                     .LeftJoin<Corecmsbrand>((usergoods, brand) => usergoods.GoodBrand == brand.Id)
                     .LeftJoin<Corecmsuserstock>((usergoods, brand, stock) => usergoods.GoodId == stock.GoodId && usergoods.UserId == stock.UserId)
                     .Where((usergoods, brand, stock) => usergoods.UserId == parm.userId)
                     .WhereIF(parm.goodsId > 0, (usergoods, brand, stock) => usergoods.GoodId == parm.goodsId)
                     .Select((usergoods, brand, stock) => new PurStockManageDetailDto
                     {
                         distributionProdId = usergoods.GoodId,
                         distributionSkuId = stock.ProductId,
                         skuId = stock.ProductId,
                         skuCode = stock.Sn,
                         skuName = stock.SkuName,
                         prodCode69 = stock.BarCode,
                         skuStocks = stock.Stock,
                         sellerSkuStocks = 0,
                         transitSkuNum = 0,
                         distributionStocks = stock.PurStock,
                         stockWarningLine = stock.StockWarn,
                         brandName = brand.Name,
                         costPrice = stock.ProductCostPrice,
                         normalPrice = stock.Vip0,
                         vip1Price = stock.Vip1,
                         vip2Price = stock.Vip2,
                         vip3Price = stock.Vip3,
                         vip4Price = stock.Vip4,
                         delFlag = stock.IsDel
                     })
                     .ToList();
            model.distributionSkuVOS = dto;
            return model;
        }

        /// <summary>
        /// 查询铺货列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<PurStockManageDto> GetPurStockManageList(PurStockManageQueryDto parm)
        {
            var response = Context.Queryable<Corecmsusergoods>()
                 .LeftJoin<Corecmsgoods>((usergoods, goods) => usergoods.GoodId == goods.Id)
                 .LeftJoin<Corecmsbrand>((usergoods, goods, brand) => usergoods.GoodBrand == brand.Id)
                 .LeftJoin<Corecmsuserstock>((usergoods, goods, brand, stock) => usergoods.GoodId == stock.GoodId && usergoods.UserId == stock.UserId)
                 .Where((usergoods, goods, brand, stock) => usergoods.UserId == parm.userId&& stock.PurStock>0)
                 .WhereIF(parm.salePriceSetted == 0, (usergoods, goods, brand, stock) => (stock.Vip0 > 0 || stock.Vip1 > 0 || stock.Vip2 > 0 || stock.Vip3 > 0 || stock.Vip4 > 0))
                 .WhereIF(parm.salePriceSetted == 1, (usergoods, goods, brand, stock) => (stock.Vip0 <= 0 && stock.Vip1 <= 0 && stock.Vip2 <= 0 && stock.Vip3 <= 0 && stock.Vip4 <= 0))
                 .WhereIF(!string.IsNullOrEmpty(parm.catetoryIds), (usergoods, goods, brand, stock) => goods.categoryArr.StartsWith(parm.catetoryIds))
                 .WhereIF(!string.IsNullOrEmpty(parm.goodName), (usergoods, goods, brand, stock) => usergoods.GoodName.Contains(parm.goodName))
                 .GroupBy((usergoods, goods, brand, stock) => new { usergoods.GoodId, goods.Image, usergoods.GoodName, goods.categoryArr, brand.Name, usergoods.CreateTime })
                 .Select((usergoods, goods, brand) => new PurStockManageDto
                 {

                     prodId = usergoods.GoodId,
                     pic = goods.Image,
                     prodName = usergoods.GoodName,
                     categoryName = goods.categoryArr,
                     brandName = brand.Name,
                     skuNum = SqlFunc.Subqueryable<Corecmsuserstock>().Where(s => s.UserId == parm.userId && s.GoodId == usergoods.GoodId).Count(),
                     totalStocks = SqlFunc.Subqueryable<Corecmsuserstock>().Where(s => s.UserId == parm.userId && s.GoodId == usergoods.GoodId).Sum(s => s.Stock ?? 0),
                     totalDistributionStocks = SqlFunc.Subqueryable<Corecmsuserstock>().Where(s => s.UserId == parm.userId && s.GoodId == usergoods.GoodId).Sum(s => s.PurStock ?? 0),
                     skuWarningNum = 0,
                     createTime = usergoods.CreateTime
                     // 可以继续添加其他属性赋值
                 })
                 //.GroupBy(t => t.prodId).Select(p => new PurStockManageDto
                 //{
                 //    prodId = usergoods.GoodId,
                 //    pic = goods.Image,
                 //    prodName = usergoods.GoodName,
                 //    categoryName = goods.categoryArr,
                 //    brandName = brand.Name,
                 //})
                 .ToPage<PurStockManageDto>(parm);

            return response;
        }

        /// <summary>
        /// 更新增值价
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>

        public bool UpdatePurStockInvalVipPrice(InvalVipPriceUpdateDto parm)
        {
            if (parm.selectedCategoryIds == null || parm.selectedCategoryIds.Count == 0)
            {
                return false;
            }

            // 查询符合条件的 goodId 集合
            var goodIds = Context.Queryable<Corecmsusergoods>()
                .LeftJoin<Corecmsuserstock>((usergoods, stock) => usergoods.GoodId == stock.GoodId)
                .LeftJoin<Corecmsgoods>((usergoods, stock, goods) => usergoods.GoodId == goods.Id)
                .Where((usergoods, stock, goods) => parm.selectedCategoryIds.Any(id => goods.categoryArr.StartsWith(id.ToString())))
                .WhereIF(parm.effectiveProducts == 0, (usergoods, stock, goods) => stock.InvalVip0 <= 0 || stock.InvalVip1 <= 0 || stock.InvalVip2 <= 0 || stock.InvalVip3 <= 0 || stock.InvalVip4 <= 0)
                 .Where((usergoods, stock, goods) => usergoods.UserId == parm.userId)
                .Select((usergoods, stock, goods) => usergoods.GoodId)
                .Distinct()
                .ToList();
            if (goodIds.Count == 0)
            {
                return false;
            }

            // 根据 goodIds 和 parm.userId 找出 corecmsuserstock 表的数据
            var userStocks = Context.Queryable<Corecmsuserstock>()
                .Where(s => s.UserId == parm.userId && goodIds.Contains(s.GoodId))
                .ToList();
            // 根据增值类型计算并更新 invalVip0 到 invalVip4 的价格
            foreach (var stock in userStocks)
            {
                if (stock.ProductCostPrice <= 0)
                {
                    continue;
                }
                if (parm.increaseType == 1)//比列
                {
                    // 按百分比计算增值
                    stock.InvalVip0 = parm.vip0Price > 0 ? stock.ProductCostPrice * (1 + parm.vip0Price / 100) : stock.InvalVip0;
                    stock.InvalVip1 = parm.vip1Price > 0 ? stock.ProductCostPrice * (1 + parm.vip1Price / 100) : stock.InvalVip1;
                    stock.InvalVip2 = parm.vip2Price > 0 ? stock.ProductCostPrice * (1 + parm.vip2Price / 100) : stock.InvalVip2;
                    stock.InvalVip3 = parm.vip3Price > 0 ? stock.ProductCostPrice * (1 + parm.vip3Price / 100) : stock.InvalVip3;
                    stock.InvalVip4 = parm.vip4Price > 0 ? stock.ProductCostPrice * (1 + parm.vip4Price / 100) : stock.InvalVip4;
                }
                else
                {
                    // 按固定值计算增值
                    stock.InvalVip0 = stock.ProductCostPrice + parm.vip0Price;
                    stock.InvalVip1 = stock.ProductCostPrice + parm.vip1Price;
                    stock.InvalVip2 = stock.ProductCostPrice + parm.vip2Price;
                    stock.InvalVip3 = stock.ProductCostPrice + parm.vip3Price;
                    stock.InvalVip4 = stock.ProductCostPrice + parm.vip4Price;
                }
            }
            // 批量更新数据
            var updateResult = Context.Updateable<Corecmsuserstock>(userStocks)
                .UpdateColumns(it => new
                {
                    it.InvalVip0,
                    it.InvalVip1,
                    it.InvalVip2,
                    it.InvalVip3,
                    it.InvalVip4,
                })
                .ExecuteCommand();
            return true;
        }

        public bool UpdateVipSalePrice(PurStockManageMasterhDto parm)
        {
            if (parm == null || parm.distributionSkuVOS == null || parm.distributionSkuVOS.Count == 0)
            {
                return false;
            }

            // 遍历明细，准备更新数据
            var updateList = new List<Corecmsuserstock>();
            foreach (var skuDto in parm.distributionSkuVOS)
            {
                var stock = Context.Queryable<Corecmsuserstock>()
                    .Where(s => s.UserId == parm.userId && s.GoodId == parm.prodId && s.ProductId == skuDto.skuId)
                    .First();

                if (stock != null)
                {
                    stock.Vip0 = skuDto.normalPrice ?? 0;
                    stock.Vip1 = skuDto.vip1Price ?? 0;
                    stock.Vip2 = skuDto.vip2Price ?? 0;
                    stock.Vip3 = skuDto.vip3Price ?? 0;
                    stock.Vip4 = skuDto.vip4Price ?? 0;

                    updateList.Add(stock);
                }
            }

            if (updateList.Count == 0)
            {
                return false;
            }

            // 批量更新数据
            var updateResult = Context.Updateable<Corecmsuserstock>(updateList)
                .UpdateColumns(it => new
                {
                    it.Vip0,
                    it.Vip1,
                    it.Vip2,
                    it.Vip3,
                    it.Vip4
                })
                .ExecuteCommand();

            return updateResult > 0;
        }

        public bool UpdateStockWarnLine(PurStockManageMasterhDto parm)
        {
            if (parm == null || parm.distributionSkuVOS == null || parm.distributionSkuVOS.Count == 0)
            {
                return false;
            }

            // 遍历明细，准备更新数据
            var updateList = new List<Corecmsuserstock>();
            foreach (var skuDto in parm.distributionSkuVOS)
            {
                var stock = Context.Queryable<Corecmsuserstock>()
                    .Where(s => s.UserId == parm.userId && s.GoodId == parm.prodId && s.ProductId == skuDto.skuId)
                    .First();

                if (stock != null)
                {
                    stock.stockWarnType = int.Parse(skuDto.stockWarnType ?? "-1");
                    stock.StockWarn = skuDto.stockWarningLine;

                    updateList.Add(stock);
                }
            }

            if (updateList.Count == 0)
            {
                return false;
            }

            // 批量更新数据
            var updateResult = Context.Updateable<Corecmsuserstock>(updateList)
                .UpdateColumns(it => new
                {
                    it.stockWarnType,
                    it.StockWarn
                })
                .ExecuteCommand();

            return updateResult > 0;
        }

        public PagedInfo<ExportPurStockManageDto> GetExportPurStockManageList(PurStockManageQueryDto parm)
        {
            var response = Context.Queryable<Corecmsusergoods>()
                 .LeftJoin<Corecmsgoods>((usergoods, goods) => usergoods.GoodId == goods.Id)
                 .InnerJoin<Corecmsuserstock>((usergoods, goods, stock) => usergoods.GoodId == stock.GoodId && usergoods.UserId == stock.UserId)
                 .LeftJoin<Corecmsuser>((usergoods, goods, stock, user) => usergoods.UserId == user.Id)

                 .Where((usergoods, goods, stock, user) => usergoods.UserId == parm.userId&&stock.PurStock>0)
                 .Select((usergoods, goods, stock, user) => new ExportPurStockManageDto
                 {
                     userName = user.UserName,
                     goodName = stock.SkuName ?? goods.Name,
                     barCode = stock.BarCode,
                     sn = stock.Sn,
                     categoryName = goods.categoryArr,
                     salePrice = stock.Vip0,
                     purStock = stock.PurStock ?? 0
                     // 可以继续添加其他属性赋值
                 })
                 .ToPage<ExportPurStockManageDto>(parm);
            return response;
        }

        public bool ImportDistribution(long userId, List<ImportPurStockDto> list2, bool append = false)
        {
            var userInfo = Context.Queryable<Corecmsuser>().Where(e => e.Id == userId).First();
            var parentUserId = userInfo.ParentId;


            var list = Context.Queryable<Corecmsuserstock>()
                       .Where((stock) => stock.UserId == userId && list2.Any(t => t.商品69码 == stock.BarCode)).ToList();
            var existingStockBarCodes = list.Select(stock => stock.BarCode).ToList();
            var newImportItems = list2.Where(item => !existingStockBarCodes.Contains(item.商品69码)).ToList();
            if (newImportItems.Count > 0)
            {
                var insertList = new List<Corecmsuserstock>();
                var insertUserGoodsList = new List<Corecmsusergoods>();
                foreach (var importItem in newImportItems)
                {
                    // 从 Corecmsproducts 表匹配数据
                    var product = Context.Queryable<Corecmsproducts>()
                        .LeftJoin<Corecmsgoods>((prod, goods) => prod.GoodsId == goods.Id)
                        .Where((prod, goods) =>
                            prod.Barcode == importItem.商品69码 && prod.IsDel == false &&
                            prod.GoodsId == goods.Id)
                        .Select((prod, goods) => new { Product = prod, Goods = goods })
                        .First();

                    var parentProduct = Context.Queryable<Corecmsuserstock>().Where(e => e.UserId == parentUserId && e.GoodId == product.Goods.Id && e.ProductId == product.Product.Id).First();

                    if (product != null)
                    {
                        // 封装 Corecmsuserstock 数据
                        var newStock = new Corecmsuserstock
                        {
                            UserId = userId,
                            GoodId = product.Product.GoodsId,
                            ProductId = product.Product.Id,
                            CreateTime = DateTime.Now,
                            Sn = product.Product.Sn,
                            BarCode = product.Product.Barcode,
                            SkuName = product.Product.SkuName,
                            PurStock = importItem.铺货数量,
                            Stock = 0,
                            MinStock = 0,
                            ProductCostPrice = (userInfo.Level == "0" ? parentProduct.Vip0 : (userInfo.Level == "1" ? parentProduct.Vip1 : (userInfo.Level == "2" ? parentProduct.Vip2 : (userInfo.Level == "3" ? parentProduct.Vip3 : parentProduct.Vip4)))), // 假设使用产品价格作为成本价
                            SkuImage = product.Goods.Image,
                            SkubrandId = product.Goods.BrandId
                        };
                        var exprod = insertList.Where(good => good.ProductId == product.Product.Id).Count();
                        if (exprod <= 0)
                        {
                            insertList.Add(newStock);
                        }

                        // 封装 Corecmsusergoods 数据
                        var newUserGoods = new Corecmsusergoods
                        {
                            UserId = userId,
                            GoodId = product.Product.GoodsId,
                            GoodName = product.Goods.Name,
                            GoodBrand = product.Goods.BrandId,
                            // 可根据实际情况补充其他字段
                            CreateTime = DateTime.Now,
                            intro = product.Goods.Intro

                        };
                        var existingUserGoods = Context.Queryable<Corecmsusergoods>().Where(ug => ug.UserId == newUserGoods.UserId && ug.GoodId == newUserGoods.GoodId).First();
                        if (existingUserGoods != null)
                        {
                            // 存在则更新
                            existingUserGoods.GoodName = newUserGoods.GoodName;
                            existingUserGoods.GoodBrand = newUserGoods.GoodBrand;
                            existingUserGoods.intro = newUserGoods.intro;
                            // 可根据实际情况更新其他字段
                            Context.Updateable(existingUserGoods).ExecuteCommand();
                        }
                        else
                        {
                            var ex = insertUserGoodsList.Where(good => good.GoodId == newUserGoods.GoodId).Count();
                            if (ex > 0) continue;
                            // 不存在则插入
                            insertUserGoodsList.Add(newUserGoods);
                        }
                    }
                }

                if (insertList.Count > 0)
                {
                    // 批量插入新数据
                    Context.Insertable(insertList).ExecuteCommand();
                }

                if (insertUserGoodsList.Count > 0)
                {
                    // 批量插入 Corecmsusergoods 新数据
                    Context.Insertable(insertUserGoodsList).ExecuteCommand();
                }
            }

            var updateList = new List<Corecmsuserstock>();

            foreach (var stock in list)
            {
                var importItem = list2.FirstOrDefault(t => (t.商品69码 == stock.BarCode));
                if (importItem != null)
                {
                    if (append)
                    {
                        // 累加 purStock
                        stock.PurStock = (stock.PurStock ?? 0) + importItem.铺货数量;
                    }
                    else
                    {
                        // 直接替换 purStock
                        stock.PurStock = importItem.铺货数量;
                    }
                    updateList.Add(stock);
                }
            }

            if (updateList.Count > 0)
            {
                // 批量更新数据
                var updateResult = Context.Updateable<Corecmsuserstock>(updateList)
                    .UpdateColumns(it => new
                    {
                        it.PurStock
                    })
                    .ExecuteCommand();

                return updateResult > 0;
            }



            return true;
        }

        /// <summary>
        /// 获取补货列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public async Task<ReStockMasterDto> GetReStockList(ReStockQueryDto parm, long loginUserId)
        {
            var dto = new ReStockMasterDto();

            var userinfo = await Context.Queryable<Corecmsuser>().Where(e => e.Id == parm.userId).FirstAsync();
            if (userinfo != null && userinfo.CreditAmt > 0)
            {
                dto.amountLimit = userinfo.CreditAmt;
            }


            var query = await Context.Queryable<Corecmsusergoods>()
                        .InnerJoin<Corecmsuserstock>((usergoods, stock) => usergoods.GoodId == stock.GoodId && usergoods.UserId == stock.UserId)
                        .LeftJoin<Corecmsuserstock>((usergoods, stock, us) => stock.ProductId == us.ProductId && us.UserId == loginUserId)
                        .LeftJoin<Corecmsgoods>((usergoods, stock, us, goods) => usergoods.GoodId == goods.Id)
                        .WhereIF(parm.goodsId.HasValue, (usergoods, stock, us, goods) => usergoods.GoodId == parm.goodsId.Value)
                        .Where((usergoods, stock, us, goods) => usergoods.UserId == parm.userId && stock.PurStock > 0)
                        //.GroupBy((usergoods, stock, goods) => new { usergoods.GoodId, usergoods.Images, goods.Name, goods.Image })
                        .Select((usergoods, stock, us, goods) => new
                        {
                            prodId = usergoods.GoodId,
                            pic = usergoods.Images ?? goods.Image,
                            prodName = goods.Name,
                            distributionProdId = usergoods.GoodId,
                            distributionSkuId = stock.ProductId,
                            skuId = stock.ProductId,
                            skuCode = stock.Sn,
                            skuName = stock.SkuName,
                            prodCode69 = stock.BarCode,
                            skuStocks = stock.Stock,
                            sellerSkuStocks = 0,
                            transitSkuNum = 0,
                            distributionStocks = stock.PurStock,
                            stockWarningLine = stock.StockWarn,
                            stockWarnType = stock.stockWarnType.ToString(),
                            brandName = "",
                            costPrice = stock.ProductCostPrice,
                            normalPrice = us.Vip0,
                            vip1Price = us.Vip1,
                            vip2Price = us.Vip2,
                            vip3Price = us.Vip3,
                            vip4Price = us.Vip4,
                            delFlag = stock.IsDel,
                            stock = stock.Stock ?? 0,
                            purstock = stock.PurStock ?? 0

                        }).ToListAsync();
            var transitOrders = Context.Queryable<Transferorder>().Where(e => e.Status == "4" && e.NewUserld == parm.userId && e.CreateTime >= DateTime.Now.AddMonths(-6)).Select(e => e.OrderId).ToList();

            var transetDetails = transitOrders != null && transitOrders.Count > 0 ? Context.Queryable<Transferorderitem>().Where(e => transitOrders.Contains(e.OrderId)).ToList() : new List<Transferorderitem>();

            // 按 prodId, pic, prodName 分组
            var groupedQuery = query.GroupBy(item => new
            {
                item.prodId,
                item.pic,
                item.prodName
            });

            // 组装数据到 ReStockMasterDto
            var distributionDetailVOS = new List<PurStockManageMasterhDto>();
            foreach (var group in groupedQuery)
            {
                var masterItem = new PurStockManageMasterhDto
                {
                    prodId = group.Key.prodId,
                    pic = group.Key.pic,
                    prodName = group.Key.prodName,
                    distributionSkuVOS = group.Select(item => new PurStockManageDetailDto
                    {
                        distributionProdId = item.distributionProdId,
                        distributionSkuId = item.distributionSkuId,
                        skuId = item.skuId,
                        skuCode = item.skuCode,
                        skuName = item.skuName,
                        prodCode69 = item.prodCode69,
                        skuStocks = item.skuStocks,
                        sellerSkuStocks = item.sellerSkuStocks,
                        transitSkuNum = transetDetails.Where(e => e.ProductId == item.skuId && e.GoodsId == item.distributionProdId).Sum(e => e.Nums),
                        distributionStocks = item.distributionStocks,
                        stockWarningLine = item.stockWarningLine,
                        stockWarnType = item.stockWarnType,
                        brandName = item.brandName,
                        costPrice = userinfo.Level == "0" ? item.normalPrice : userinfo.Level == "1" ? item.vip1Price : userinfo.Level == "2" ? item.vip2Price : userinfo.Level == "3" ? item.vip3Price : item.vip4Price,//item.costPrice,
                        normalPrice = item.normalPrice,
                        vip1Price = item.vip1Price,
                        vip2Price = item.vip2Price,
                        vip3Price = item.vip3Price,
                        vip4Price = item.vip4Price,
                        delFlag = item.delFlag,
                        purqty = item.stock <= item.purstock ? item.purstock - item.stock : 0
                    }).ToList()
                };
                masterItem.distributionSkuVOS.ForEach(item =>
                {
                    item.purqty = item.skuStocks + item.transitSkuNum <= item.distributionStocks ? item.distributionStocks - (item.skuStocks + item.transitSkuNum) : 0;

                });

                distributionDetailVOS.Add(masterItem);
            }

            dto.details = distributionDetailVOS;
            return dto;

        }


        public bool ReStockAdd(List<PurStockManageMasterhDto> parm, long loginUserId)
        {
            var userId = parm[0].userId;

            var newUser = _corecmsuserService.Queryable().Where(u => u.Id == userId).First();

            var alldata = new List<PurStockManageDetailDto>();
            foreach (var item in parm)
            {
                foreach (var item2 in item.distributionSkuVOS)
                {
                    if (item2.purqty > 0)
                        alldata.Add(item2);
                }
            }
            var skuIds = alldata.Select(e => e.skuId).Distinct().ToList();

            var products =
                Context.Queryable<Corecmsusergoods>()
                .LeftJoin<Corecmsproducts>((usergoods, prod) => usergoods.UserId == loginUserId && prod.GoodsId == usergoods.GoodId)
                .Where((usergoods, prod) => usergoods.UserId == loginUserId && skuIds.Contains(prod.Id))
                .Select((usergoods, prod) => prod).ToList();

            //取客户价格
            var usList = Context.Queryable<Corecmsuserstock>().Where(it => it.UserId == loginUserId && skuIds.Contains(it.ProductId)).ToList();

            //小仓调配单 olduserId 76 NewuserId 82
            var transferOrder = new Transferorder();
            List<Transferorderdetail> TransferorderdetailNav = new List<Transferorderdetail>();
            List<Transferorderitem> TransferorderitemNav = new List<Transferorderitem>();
            transferOrder.TransferorderitemNav = TransferorderitemNav;
            transferOrder.TransferorderdetailNav = TransferorderdetailNav;

            transferOrder.OldUserId = loginUserId;
            transferOrder.NewUserld = userId;
            transferOrder.UserId = loginUserId;
            transferOrder.Type = "0";
            transferOrder.CreateTime = DateTime.Now;

            foreach (var item in alldata)
            {
                var prod = products.FirstOrDefault(e => e.Id == item.skuId);
                TransferorderdetailNav.Add(new Transferorderdetail()
                {
                    ProductId = item.skuId,
                });
                decimal price = item.costPrice ?? 0;
                var us = usList.FirstOrDefault(u => u.ProductId == item.skuId);
                if (us != null)
                {
                    switch (newUser.Level)
                    {
                        case "0":
                            price = us.Vip0;
                            break;
                        case "1":
                            price = us.Vip1;
                            break;
                        case "2":
                            price = us.Vip2;
                            break;
                        case "3":
                            price = us.Vip3;
                            break;
                        case "4":
                            price = us.Vip4;
                            break;
                    }
                }
                TransferorderitemNav.Add(new Transferorderitem()
                {
                    ProductId = item.skuId,
                    GoodsId = item.distributionProdId,
                    Sn = item.skuCode,
                    BarCode = item.prodCode69,
                    Price = price,
                    ImageUrl = prod != null ? prod.Images : "",
                    Nums = item.purqty ?? 0,
                    Amount = price * (item.purqty ?? 0),
                    Addon = item.skuName
                });
            }

            return _TransferorderService.AddTransferorder2(transferOrder).status;




            //foreach (var item in alldata)
            //{
            //    var distributionProdId = item.distributionProdId;
            //    var distributionSkuId = item.distributionSkuId;


            //    // 查询并更新 Corecmsuserstock 表
            //    var updateResult = Context.Updateable<Corecmsuserstock>()
            //        .SetColumns(it => new Corecmsuserstock
            //        {
            //            PurStock = it.PurStock+ item.purqty
            //        })
            //        .Where(it => it.GoodId == distributionProdId && it.ProductId == distributionSkuId && it.UserId == userId)
            //        .ExecuteCommand();
            //}

            //return true;
        }

        public PagedInfo<ProductStockDto> ExportList(CorecmsuserstockQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                 .LeftJoin<Corecmsgoods>((aprod, goods) => aprod.GoodId == goods.Id)
                 .LeftJoin<Corecmsproducts>((aprod, goods, prod) => aprod.ProductId == prod.Id)
                 .LeftJoin<Corecmsbrand>((aprod, goods, prod, brand) => goods.BrandId == brand.Id)
                 .Where((aprod, goods, prod, brand) => aprod.UserId == parm.UserId)
                 .WhereIF(parm.GoodsId.HasValue, (aprod, goods, prod, brand) => aprod.GoodId == parm.GoodsId.Value)
                 .WhereIF(!string.IsNullOrEmpty(parm.categoryArr), (aprod, goods, prod, brand) => goods.categoryArr.StartsWith(parm.categoryArr))
                 .WhereIF(parm.HasStock, (aprod, goods, prod, brand) => aprod.Stock > 0 || aprod.MinStock > 0)
                 //.WhereIF(parm.mini.HasValue && parm.mini == 1, (aprod, goods, prod) => aprod.MinStock > 0)
                 .WhereIF(!string.IsNullOrEmpty(parm.sn), (aprod, goods, prod, brand) => prod.Sn.Contains(parm.sn) || prod.SpesDesc.Contains(parm.sn) || prod.Barcode.Contains(parm.sn))
                .Select((aprod, goods, prod, brand) => new
                {
                    Aprod = aprod,
                    Goods = goods,
                    Prod = prod,
                    Brand = brand
                })
                .ToPage(parm);

            var codes = Context.Queryable<Prodinfo>()
                .Where(pi => pi.UserId == parm.UserId && pi.IsReturn == 0 && pi.Status == 1)
                .ToList();


            var result = response.Result.Select(item =>
            {
                var aprod = item.Aprod;
                var goods = item.Goods;
                var prod = item.Prod;
                var brand = item.Brand;

                var snCodes = codes
                    .Where(pi => pi.ProductId == prod.Id && pi.UserId == aprod.UserId && pi.GoodsId == aprod.GoodId)
                    .Select(pi => pi.SnCode)
                    .ToList();

                return new ProductStockDto
                {
                    Id = aprod.Id,
                    SkuImage = !string.IsNullOrWhiteSpace(aprod.SkuImage) ? aprod.SkuImage : goods.Image,
                    Sn = prod.Sn,
                    ProductId = prod.Id,
                    SkuName = prod.SkuName,
                    Stock = aprod.Stock ?? 0,
                    MinStock = aprod.MinStock ?? 0,
                    VIP0 = aprod.Vip0,
                    VIP1 = aprod.Vip1,
                    VIP2 = aprod.Vip2,
                    VIP3 = aprod.Vip3,
                    VIP4 = aprod.Vip4,
                    BarCode = prod.Barcode,
                    CategoryName = goods.categoryArr,
                    CostPrice = aprod.ProductCostPrice,
                    Atrr = "铺货商品",
                    SkuLocation = aprod.SkuLocation,
                    Marketable = aprod.Marketable ?? 0,
                    CategoryId = goods.GoodsCategoryId,
                    FirstCategoryId = goods.GoodsFirstCategoryId,
                    SecondCategoryId = goods.GoodsSecondCategoryId,
                    SkuBrandId = aprod.SkubrandId.HasValue ? aprod.SkubrandId.Value : goods.BrandId,
                    SkuBrandName = brand.Name,
                    TotalStock = (aprod.Stock ?? 0) + (aprod.MinStock ?? 0),
                    CreateTime = aprod.CreateTime,
                    SnCodes = string.Join(" ", snCodes)
                };
            }).ToList();
            //处理分类
            var categoryIds = result.Select(e => e.CategoryName).ToList();

            if (categoryIds.Count() > 0)
            {
                var categoryArr = new List<string>();
                categoryIds.ForEach(e => categoryArr.AddRange(e.Split(',')));

                var categoryList = Context.Queryable<Corecmsgoodscategory>().Where(e => categoryArr.Contains(e.Id.ToString())).ToList();
                foreach (var dto in result)
                {
                    var categoryArrOne = dto.CategoryName.Split(',');
                    dto.CategoryName = "";
                    for (var i = 0; i < categoryArrOne.Length; i++)
                    {
                        var firstCategory = categoryList.FirstOrDefault(e => e.Id.ToString() == categoryArrOne[i]);
                        if (firstCategory != null)
                        {
                            dto.CategoryName += firstCategory.Name + "/";
                        }
                    }
                    if (!string.IsNullOrEmpty(dto.CategoryName))
                        dto.CategoryName = dto.CategoryName.TrimEnd('/');
                }
            }
            var pageinfo = new PagedInfo<ProductStockDto>();
            pageinfo.Result = result;
            pageinfo.TotalNum = response.TotalNum;
            pageinfo.PageIndex = response.PageIndex;
            pageinfo.PageSize = response.PageSize;
            return pageinfo;


        }

        public PagedInfo<ProductMiniStockDto> ExportMiniList(CorecmsuserstockQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                 .InnerJoin<Corecmsuser>((aprod, user) => aprod.UserId == user.Id && user.ParentId == parm.UserId)
                 .LeftJoin<Corecmsgoods>((aprod, user, goods) => aprod.GoodId == goods.Id)
                 .LeftJoin<Corecmsproducts>((aprod, user, goods, prod) => aprod.ProductId == prod.Id)
                 .LeftJoin<Corecmsbrand>((aprod, user, goods, prod, brand) => goods.BrandId == brand.Id)
                 .Where((aprod, user, goods, prod, brand) => aprod.Stock > 0)
                 .WhereIF(!string.IsNullOrEmpty(parm.categoryArr), (aprod, user, goods, prod, brand) => goods.categoryArr.StartsWith(parm.categoryArr))
                 .WhereIF(parm.cusUserId.HasValue, (aprod, user, goods, prod, brand) => aprod.UserId == parm.cusUserId)
                 .WhereIF(!string.IsNullOrEmpty(parm.sn), (aprod, user, goods, prod, brand) => prod.Sn.Contains(parm.sn))
                .Select((aprod, user, goods, prod, brand) => new
                {
                    Aprod = aprod,
                    Goods = goods,
                    Prod = prod,
                    Brand = brand,
                    User = user
                })
                .ToPage(parm);
            var codes = Context.Queryable<Prodinfo>()
    .Where(pi => pi.UserId == parm.UserId && pi.IsReturn == 0 && pi.Status == 1)
    .ToList();

            var result = response.Result.Select(item =>
            {
                var aprod = item.Aprod;
                var goods = item.Goods;
                var prod = item.Prod;
                var brand = item.Brand;
                var user = item.User;
                //var snCodes = Context.Queryable<Prodinfo>()
                //    .Where(pi => pi.ProductId == prod.Id && pi.UserCusId == aprod.UserId && pi.GoodsId == aprod.GoodId)
                //    .Select(pi => pi.SnCode)
                //    .ToList();

                var snCodes = codes
    .Where(pi => pi.ProductId == prod.Id && pi.UserId == aprod.UserId && pi.GoodsId == aprod.GoodId)
    .Select(pi => pi.SnCode)
    .ToList();

                return new ProductMiniStockDto
                {
                    Id = aprod.Id,
                    Sn = prod.Sn,
                    ProductId = prod.Id,
                    SkuName = prod.SkuName,
                    MinStock = aprod.Stock ?? 0,
                    BarCode = prod.Barcode,
                    CategoryName = goods.categoryArr,
                    SkuLocation = aprod.SkuLocation,
                    CategoryId = goods.GoodsCategoryId,
                    FirstCategoryId = goods.GoodsFirstCategoryId,
                    SecondCategoryId = goods.GoodsSecondCategoryId,
                    SkuBrandId = aprod.SkubrandId.HasValue ? aprod.SkubrandId.Value : goods.BrandId,
                    SkuBrandName = brand.Name,
                    UserName = user.UserName,
                    SnCodes = string.Join(" ", snCodes)
                };
            }).ToList();
            //处理分类
            var categoryIds = result.Select(e => e.CategoryName).ToList();

            if (categoryIds.Count() > 0)
            {
                var categoryArr = new List<string>();
                categoryIds.ForEach(e => categoryArr.AddRange(e.Split(',')));

                var categoryList = Context.Queryable<Corecmsgoodscategory>().Where(e => categoryArr.Contains(e.Id.ToString())).ToList();
                foreach (var dto in result)
                {
                    var categoryArrOne = dto.CategoryName.Split(',');
                    dto.CategoryName = "";
                    for (var i = 0; i < categoryArrOne.Length; i++)
                    {
                        var firstCategory = categoryList.FirstOrDefault(e => e.Id.ToString() == categoryArrOne[i]);
                        if (firstCategory != null)
                        {
                            dto.CategoryName += firstCategory.Name + "/";
                        }
                    }
                    if (!string.IsNullOrEmpty(dto.CategoryName))
                        dto.CategoryName = dto.CategoryName.TrimEnd('/');
                }
            }
            var pageinfo = new PagedInfo<ProductMiniStockDto>();
            pageinfo.Result = result;
            pageinfo.TotalNum = response.TotalNum;
            pageinfo.PageIndex = response.PageIndex;
            pageinfo.PageSize = response.PageSize;
            return pageinfo;


        }
    }
}